package com.ssy.lingxi.settle.accounts.serviceimpl;

import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.settle.accounts.entity.ReconciliationFileDO;
import com.ssy.lingxi.settle.accounts.model.vo.request.ReconciliationFileSaveVo;
import com.ssy.lingxi.settle.accounts.model.vo.response.ReconciliationFileQueryVO;
import com.ssy.lingxi.settle.accounts.repository.ReconciliationFileRepository;
import com.ssy.lingxi.settle.accounts.service.IReconciliationFileService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 对账单附件接口实现
 * @author Saske
 * @date 2021/12/22
 * @version 2.0.0
 */
@Service
public class ReconciliationFileServiceImpl implements IReconciliationFileService {

    @Resource
    private ReconciliationFileRepository fileRepository;

    /**
     * 批量新增对账单附件
     * @author Saske
     * @date 2021/12/22
     * @param files : 附件信息集合
     **/
    @Override
    @Transactional
    public void addReconciliationFile(String reconciliationNo , List<ReconciliationFileSaveVo> files) {
        if (CollectionUtils.isNotEmpty(files))
            files.forEach(r -> {
                ReconciliationFileDO fileDO = new ReconciliationFileDO();
                fileDO.setReconciliationNo(reconciliationNo); // 对账单号
                fileDO.setFileName(r.getFileName()); // 账单明细附件名称
                fileDO.setFileUrl(r.getFileUrl()); // 账单明细附件
                // 保存附件
                fileRepository.saveAndFlush(fileDO);
            });
        Wrapper.success();
    }

    /**
     * 根据对账单号查询对账单附件
     * @author Saske
     * @date 2021/12/22
     * @param reconciliationNo: 对账单号
     * @return 对账单附件列表
     **/
    @Override
    public List<ReconciliationFileQueryVO> getFileList(String reconciliationNo) {
        List<ReconciliationFileDO> fileDOS = fileRepository.findAllByReconciliationNo(reconciliationNo);

        return fileDOS.stream().map(r -> {
            ReconciliationFileQueryVO queryVO = new ReconciliationFileQueryVO();
            queryVO.setFileName(r.getFileName());
            queryVO.setFileUrl(r.getFileUrl());
            return queryVO;
        }).collect(Collectors.toList());
    }

    /**
     * 根据对账单号删除对账单附件
     * @author Saske
     * @param reconciliationNo : 对账单号
     **/
    @Override
    @Transactional
    public void deleteReconciliationFile(String reconciliationNo) {
        fileRepository.deleteByReconciliationNo(reconciliationNo);
    }
}
